<template>
  <a-spin :spinning="spinning">
    <a>
      <a-button
        type="primary"
        v-if="!record"
        :loading="loading"
        @click="getData"
        class="float-right"
        :disabled="Archive == 1"
      >
        设置违约
      </a-button>
      <a-button type="link" :loading="loading" v-else @click="getData">查看</a-button>
      <a-modal v-model="dialog" title="设置违约" :width="800">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :hideRequiredMark="true"
        >
          <div class="grid grid-cols-2">
            <a-form-model-item label="违约类型：" prop="detail">
              <a-select v-model="form.detail" :disabled="!!record" @change="getState">
                <a-select-option :value="item.value" v-for="item in calcTypes" :key="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </div>
          <div class="grid grid-cols-2">
            <a-form-model-item label="开始日期：" prop="startdata">
              <a-date-picker
                v-model="form.startdata"
                @change="change"
                :disabled-date="disabledDate"
                :disabled="!!record && readOnly"
              />
            </a-form-model-item>
            <a-form-model-item label="完成日期：" prop="enddata">
              <a-date-picker v-model="form.enddata" :disabled-date="disabledDate" :disabled="!!record && readOnly" />
            </a-form-model-item>
          </div>
          <div class="grid grid-cols-2" v-if="form.detail != 6">
            <a-form-model-item label="月份选择：" prop="mouth">
              <a-select v-model="form.mouth" @change="choose" :disabled="!!record && readOnly">
                <a-select-option :value="item" v-for="item in month" :key="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="金额：">
              <m-input-number disabled v-model="amount" style="width:200px" />
            </a-form-model-item>
          </div>
          <div v-if="form.detail == 6">
            <div class="grid grid-cols-2">
              <a-form-model-item label="违约本金金额：">
                <m-input-number v-model="form.principal" style="width:200px" :disabled="!!record && readOnly" />
              </a-form-model-item>
              <a-form-model-item label="违约资金成本：">
                <m-input-number v-model="form.capital" style="width:200px" :disabled="!!record && readOnly" />
              </a-form-model-item>
            </div>
            <div class="grid grid-cols-2">
              <a-form-model-item label="贷款限额费：">
                <m-input disabled v-model="form.limitRate" />
              </a-form-model-item>
              <a-form-model-item label="贷款限额费付款方式：">
                <a-input disabled v-model="form.limitPayType" />
              </a-form-model-item>
            </div>
            <div class="grid grid-cols-2">
              <a-form-model-item label="生效开始日期：">
                <a-date-picker v-model="form.limitStartDate" disabled />
              </a-form-model-item>
              <a-form-model-item label="生效日期：">
                每月<a-input-number v-model="form.limitDay" disabled />号
              </a-form-model-item>
            </div>
          </div>
        </a-form-model>
        <template slot="footer">
          <a-button v-if="!record" key="back" @click="dialog = false">
            取消
          </a-button>
          <a-button v-else-if="Archive != 1" type="primary" @click="readOnly = false" v-action:update>修改</a-button>
          <a-button v-if="!record" key="submit" type="primary" @click="submit">
            确定
          </a-button>
          <a-button v-else-if="Archive != 1" type="primary" @click="submit" v-action:update>保存</a-button>
        </template>
      </a-modal>
    </a>
  </a-spin>
</template>
<script>
// import { calcType } from '@/dict'
import {
  getDetailList,
  getMonth,
  getAmount,
  createDfault,
  getDfault,
  updataDfault,
  getFeeData,
  getList,
  getDefaultState
} from '@/api/common'
import moment from 'moment'
import { limitFeeTypes } from '@/dict'
import { commonRule, dateRule } from '@/utils/rules'
import mInputNumber from '@/com/mInputNumber.vue'
export default {
  components: { mInputNumber },
  name: 'changecalc',
  props: ['record'],
  data: () => ({
    spinning: false,
    dialog: false,
    loading: false,
    Archive: 0,
    month: [],
    mouths: [],
    calcTypes: [{ text: '整体违约', value: 6 }],
    labelCol: { span: 9 },
    wrapperCol: { span: 13 },
    amount: 0,
    Day: '',
    start: null,
    readOnly: true,
    limitCalcType: 0,
    form: {
      detail: 6,
      startdata: '',
      enddata: '',
      mouth: '',
      principal: '',
      capital: '',
      limitRate: '',
      limitPayType: '',
      limitStartDate: '',
      limitDay: ''
    },
    rules: {
      detail: commonRule,
      startdata: dateRule,
      enddata: dateRule,
      mouth: commonRule,
      principal: commonRule,
      capital: commonRule
    },
    pagination: {
      total: 1,
      pageSize: 20
    }
  }),
  watch: {
    dialog(v) {
      if (v) {
        this.getState()
      }
    }
  },
  mounted() {
    this.getArchive()
  },
  methods: {
    disabledDate(endValue) {
      const startValue = this.start
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    change() {
      this.form.limitStartDate = this.form.startdata
      if (this.limitCalcType == 1) {
        this.form.limitDay = 1
      } else {
        this.form.limitDay = moment(this.form.startdata).date()
      }
    },
    async getData() {
      this.loading = true
      const id = this.$route.query.id
      //获取贷款限额费等
      const feeData = await getFeeData({ projectId: id })
      this.form.capital = feeData.result.data.capital
      this.form.principal = feeData.result.data.principal
      this.form.limitRate = feeData.result.data.limitRate
      this.form.limitPayType = limitFeeTypes.find(el => el.value == feeData.result.data.limitPayType)?.text
      //获取违约类型
      this.calcTypes = [{ text: '整体违约', value: 6 }]
      const res = await getDetailList(id)
      const _form = res.result.data
      this.limitCalcType = _form.loanData?.limitCalcType
      if (_form.loanData.interestPayType == 1) {
        this.calcTypes.push({ text: '月付利息违约', value: 2 })
      }
      const fee = _form.loanData.fee
      fee.forEach(el => {
        if (el.feeType == 1) {
          if (el.feePayType == 2) {
            this.calcTypes.push({ text: '月付贷款限额费违约', value: 3 })
          }
        }
        if (el.feeType == 3) {
          if (el.feePayType == 2) {
            this.calcTypes.push({ text: '月付其他费用违约', value: 5 })
          }
        }
      })
      //获取月份
      this.month = []
      const _month = {
        projectId: this.$route.query.id
      }
      const month = await getMonth(_month)
      month.result.data.forEach(el => {
        this.mouths.push(el)
        const day = moment(el * 1000).format('YYYY-MM')
        this.month.push(day)
        // console.log(this.month)
      })
      if (this.record) {
        const form = {
          page: 1,
          limit: this.pagination.pageSize,
          projectId: this.$route.query.id,
          id: this.record.id
        }
        const res = await getDfault(form)
        const data = res.result.data.list[0]
        this.form.detail = data.detail
        this.form.mouth = moment(data.mouth * 1000).format('YYYY-MM')
        this.form.limitStartDate = this.form.startdata = moment(data.startdata * 1000)
        this.form.limitDay = moment(data.startdata * 1000).date()
        this.form.enddata = moment(data.enddata * 1000)
        this.amount = data.amount
      }
      this.loading = false
      this.dialog = true
    },
    async getArchive() {
      const id = this.$route.query.id
      const r = await getDetailList(id)
      this.Archive = r.result.data.Archive
    },
    async getState() {
      this.spinning = true
      const form = {
        page: 1,
        limit: 1,
        projectIds: this.$route.query.id
      }
      const resTime = await getList(form)
      const Time = resTime.result.data.list[0]
      const res = await getDefaultState({ projectId: this.$route.query.id })
      const data = res.result.data
      // console.log(data, Time.firstLoanTime)
      if (data.interestPayType == 1 && data.date == 0) {
        this.start = Time.firstLoanTime ? moment(Time.firstLoanTime * 1000) : null
      } else {
        this.start = data.date ? moment(data.date * 1000) : null
      }
      this.spinning = false
      // console.log(this.start)
    },
    async choose() {
      //获取金额
      const v = this.mouths.find(el => {
        const month = moment(el * 1000).format('YYYY-MM')
        return month == this.form.mouth
      })
      console.log(this.form.detail)
      const _amount = {
        projectId: this.$route.query.id,
        mouth: v,
        detail: this.form.detail
      }
      const res = await getAmount(_amount)
      this.amount = res.result.data
    },
    submit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const projectId = Number(this.$route.query.id)
          const amount = this.amount
          // console.log(amount)
          const form = Object.assign({ projectId, amount }, this.form)
          form.mouth = this.mouths.find(el => {
            const month = moment(el * 1000).format('YYYY-MM')
            if (month == this.form.mouth) return el
          })
          form.mouth = form.mouth ? form.mouth : 0
          form.startdata = Number(form.startdata.startOf('day').format('X'))
          form.limitStartDate = form.startdata
          form.enddata = Number(form.enddata.startOf('day').format('X'))
          form.limitPayType = limitFeeTypes.find(el => el.text == form.limitPayType)?.value
          // console.log(form)
          if (this.record) {
            await updataDfault(this.record.id, form)
          } else {
            await createDfault(form)
            this.form = {
              detail: 6,
              startdata: '',
              enddata: '',
              mouth: '',
              principal: '',
              capital: '',
              limitRate: '',
              limitPayType: '',
              limitStartDate: '',
              limitDay: ''
            }
          }
          this.dialog = false
          this.$emit('update')
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped></style>
